import { Injectable } from '@nestjs/common'
import { DataSource, Table, TableColumn } from 'typeorm'
import { ModelSchema } from '../entities/model-schema.entity'
import { FieldDefinition } from '../entities/field-definition.entity'

/**
 * 动态表结构生成服务
 * 用于根据模型定义自动创建 MySQL 表
 */
@Injectable()
export class TableGeneratorService {
  constructor(private dataSource: DataSource) {}

  /**
   * 根据模型定义动态创建 MySQL 表
   * @param model 业务模型定义
   */
  async createTableForModel(model: ModelSchema) {
    const queryRunner = this.dataSource.createQueryRunner()
    await queryRunner.connect()
    const tableName = model.name.toLowerCase()

    // 检查表是否已存在
    const hasTable = await queryRunner.hasTable(tableName)
    if (hasTable) {
      await queryRunner.release()
      throw new Error(`表 ${tableName} 已存在`)
    }

    // 字段类型映射与扩展
    const columns: TableColumn[] = [
      new TableColumn({
        name: 'id',
        type: 'varchar',
        length: '36',
        isPrimary: true,
        isNullable: false,
      }),
      ...model.fields.map((field: FieldDefinition) => {
        let type = 'varchar'
        let length: string | undefined = '255'
        switch (field.type) {
          case 'string':
            type = 'varchar'
            length = '255'
            break
          case 'number':
            type = 'int'
            length = undefined
            break
          case 'boolean':
            type = 'tinyint'
            length = '1'
            break
          case 'date':
            type = 'datetime'
            length = undefined
            break
          case 'text':
            type = 'text'
            length = undefined
            break
          case 'json':
            type = 'json'
            length = undefined
            break
          case 'decimal':
            type = 'decimal'
            length = '18,2'
            break
          default:
            type = 'varchar'
            length = '255'
        }
        return new TableColumn({
          name: field.name,
          type,
          length,
          isNullable: !field.required,
        })
      }),
      new TableColumn({
        name: 'created_at',
        type: 'datetime',
        isNullable: false,
        default: 'CURRENT_TIMESTAMP',
      }),
      new TableColumn({
        name: 'updated_at',
        type: 'datetime',
        isNullable: false,
        default: 'CURRENT_TIMESTAMP',
        onUpdate: 'CURRENT_TIMESTAMP',
      }),
    ]

    // 创建表
    await queryRunner.createTable(
      new Table({
        name: tableName,
        columns,
      }),
    )
    await queryRunner.release()
  }
}
